// ==UserScript==
// @name           SpaceWars
// @description    autoplayer for the SpaceWars game
// @namespace      facebook
// @version        2.0.5
// @include        http://apps.facebook.com/spacewarsgame/*
// @author         blannie
// @contributor	   colin1497
// ==/UserScript==

var settingsOpen = GM_getValue('settingsOpen', false);
var logOpen = GM_getValue('logOpen', false);
var delay = 10000; //how long to wait between logic loops
var flag = 0; //this flag is used for execution detection.  Setting the flag will prevent further autoplay options from happening during this cycle to ensure the current action completes.
var petvisit = GM_getValue('petvisit', 0); //this will set a petvisit flag every *petvisitfrequency* loads
var petvisitfrequency = 100; //this sets the number of reloads between pet visits, in the future this could be added to the config
var killhealth = 31 // value below which to heal immediately so you don't get killed
var bankgold; //variable to keep gold in bank
var totalgold; //variable to keep total gold in bank and not in bank
var currentTime = new Date();
var lastPlayTime = eval(GM_getValue('lastPlayTime', 0));
var reloadTimer;
var logicTimer;
var winCounter = GM_getValue('winCounter', 0);
var lossCounter= GM_getValue('lossCounter', 0);
var bestProperty = { id:false, roi:0, row:0 };
var nextProperty = GM_getValue('nextProperty', 0);
var SCRIPT = {
	url: 'http://userscripts.org/scripts/source/20648.user.js',
	version: '2.0.5',
	name: 'spacewarsgame',
	appID: 'app36842288331',
	money: 'credit',
	clan: 'fleet',
	presentationurl: 'http://userscripts.org/scripts/show/20648'
};

//---------------  Set up a reload timer in case the logic falls down or we get the FB error page
if (GM_getValue('autoClick', '') == "checked" && GM_getValue('paused')==0)
	{
	reload()
	}
// if we haven't played in more than 2X the max reload frequency, reset petvisit.
if ((currentTime-lastPlayTime)>(GM_getValue('r2', 300))*2000)
	{
 	petvisit=0;
	}
// store currentTime as lastPlayTime if we're not paused
if (GM_getValue('paused')==0)
	{
	GM_setValue('lastPlayTime', uneval(currentTime));
	}


var image = '';
var missions = new Array(
// Name , Energy , Tab , Item on tab, form ID, experience

["Rescue Stranded Miners",1,1,0,1,1], //1
["Repel Space Pirates",3,1,1,2,3], //2
["Smuggle Illicit Goods",5,1,2,3,5], //3
["Clear asteroid field",6,1,3,4,7], //4
["Destroy Alien Nest",7,1,4,5,8], //5
["Excavate remnants of alien civilization",1,1,5,11,1], //11
["Mine comet tail",2,1,6,12,2], //12

["Free Outer Colony Prisoners",10,2,0,6,10], // 6
["Sell Ammunition to Rebels",15,2,1,7,15], // 7
["Prevent an ambassador's assassination",5,2,2,13,5], //13
["Prevent android uprising ",6,2,3,14,6], //14

["Intercept Interstellar Gold Shipment",18,3,0,8,22], //8
["Investigate anomalous planet",8,3,1,15,10], //15
["Assassinate Galactic Dictator",25,3,2,9,30], // 9
["Pacify warring factions",13,3,3,16,18], //16

["Win an interstellar race",15,4,0,17,20], //17
["Infiltrate Imperial research networks",25,4,1,18,35], //18
["Invade Planet",30,4,2,10,35], //10
["Fly through wormhole",35,4,3,19,50], //19
["Thwart Imperial Coup",40,5,4,20,60]  //20
);

var missionTabs = new Array(
["Space Cadet (Levels 1-4)"],
["Rookie (Levels 5-8)"],
["Officer (Levels 9-14)"],
["Commander (Levels 15-25)"]
["Bogus (Levels 999+)"]
);

var curTabMastery = new Array();
var fightUsers = new Array();
var fightDeadmeat= new Array(); //People I can win against
var fightToomuch = new Array(); //People who have beaten me

var XMLHttpFactories = [
    function () {return new XMLHttpRequest()},
    function () {return new ActiveXObject("Msxml2.XMLHTTP")},
    function () {return new ActiveXObject("Msxml3.XMLHTTP")},
    function () {return new ActiveXObject("Microsoft.XMLHTTP")}
];

document.getElementsByXPath = function(sValue){ var aResult = new Array();var a = this.evaluate(sValue, ((arguments.lenth > 1) ? arguments[1] : this), null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);for ( var i = 0 ; i < a.snapshotLength ; i++ ){aResult.push(a.snapshotItem(i));}return aResult;};

//Get absolute banner position
bannerTop =   getPositionTop(document.getElementById(SCRIPT.appID+'_banner_row')); //140
bannerLeft =  getPositionLeft(document.getElementById(SCRIPT.appID+'_banner_row')); // 300
var pauseButton = document.createElement("div");

// ---------------------------- Get parsed global variables ------------------//

var alliance =  parseInt(document.body.innerHTML.split('me crew (')[1]);
var gold = document.getElementById(SCRIPT.appID+'_stats_table').innerHTML.split('$')[1];
	gold = parseInt(gold.replace(/,/g, ''));
var health = parseInt(document.getElementById(SCRIPT.appID+'_current_health').innerHTML);
var maxenergy = document.getElementById(SCRIPT.appID+'_current_energy').parentNode.innerHTML.substring(document.getElementById(SCRIPT.appID+'_current_energy').parentNode.innerHTML.indexOf(">/")+2);
var maxStamina = document.getElementById(SCRIPT.appID+'_current_stamina').parentNode.innerHTML.substring(document.getElementById(SCRIPT.appID+'_current_stamina').parentNode.innerHTML.indexOf(">/")+2);
var energy = parseInt(document.getElementById( SCRIPT.appID+'_current_energy').innerHTML);
var stamina = parseInt(document.getElementById( SCRIPT.appID+'_current_stamina').innerHTML);
var experience = document.getElementById(SCRIPT.appID+'_stats_table').childNodes[1].childNodes[0].childNodes[9].childNodes[1].childNodes[3].innerHTML.substring(0,document.getElementById(SCRIPT.appID+'_stats_table').childNodes[1].childNodes[0].childNodes[9].childNodes[1].childNodes[3].innerHTML.indexOf("/"));
var nextlevelexperience = document.getElementById(SCRIPT.appID+'_stats_table').childNodes[1].childNodes[0].childNodes[9].childNodes[1].childNodes[3].innerHTML.substring(document.getElementById(SCRIPT.appID+'_stats_table').childNodes[1].childNodes[0].childNodes[9].childNodes[1].childNodes[3].innerHTML.indexOf("/")+1);
var experiencetolevel= nextlevelexperience - experience;

// ---------------------------- menu global variables ------------------------------------//

var settingsButton
var viewLogButton
var clrLogButton
var settingsBox
var logBox
var versionBox
var autoClick
var refreshTimes
var autoProperty
var autoMission
var missionMastery 
var selectMission
var choiceTab
var choice
var autoBank
var bankConfig
var bankKeep
var autoHeal
var healthLevel
var healthRage
var updateButton
var autoFight
var fightMinimum
var fightRandom
var fightLevel
var fightClanSize
var freshMeat
var fightList
var autoTreasure
var autoPet
var autoStats
var statAtt
var statDef
var statEnergy
var statHP
var statStrength
var autoIsland
var saveButton
var saveNotification
var buyCrewProperty
   


//Grab the last known request form ID
var reqID = GM_getValue('reqformID',false);

//If we don't have a reqID or its older than a day, grab a fresh one.
if (!reqID)
{
	if (location.href.indexOf(SCRIPT.name+'/recruit') != -1)
	{
		Array.forEach(document.getElementsByTagName("input"),
			function(obj)
			{
				if (obj.id.indexOf('mfs_typeahead_req_form_') != -1)
				{
					GM_setValue('reqformID',obj.id.replace('mfs_typeahead_req_form_',''));
					return;
				}
			}
		);
	}
	else
		window.location = "http://apps.facebook.com/"+SCRIPT.name+"/recruit.php";
	return;
}

/*
var members = document.getElementsByXPath("//a[contains(@href,'/"+SCRIPT.name+"/stats.php?user=')]");
//First link is always yourself from the 'my stats' link at the top
 Array.forEach(members,
	 function(member){
		var mobid = member.href.match(/\d+$/);
		var newImg = document.createElement("img");
		newImg.setAttribute("src", image);
		newImg.addEventListener('click',invitePlayer(mobid), false);
		member.parentNode.insertBefore(newImg,member);
	 }
	 );
*/
	 




//***********************************************************
//-------------Logic here runs every page reload--------------
//***********************************************************

// --------------  Call the pause/unpause setup function ----------------//
pause()
// --------------  Build the configuration and log windows --------//
buildmenus()
// --------------  Parse whatever window we're on and log ---------//
parseandlog()
// --------------  Scan the fight list any time we happen to be on the fight page
if (GM_getValue('fightUsers', '') != '')
	{
	fightUsers=eval(GM_getValue('fightUsers', ''));
	}
if (location.href.indexOf(SCRIPT.name+'/fight') != -1)
	{
	scanfightlist()
	}
// --------------  If we're on the properties page, put data on the screen
if (location.href.indexOf(SCRIPT.name+'/properties') != -1)
	{
	propertydata()
	}
//---------------  Decrement petvisit every load
petvisit = petvisit - 1
if (petvisit < 0)
	{
	petvisit = 0;
	}
//---------------  Store pet visit value for next page load
GM_setValue('petvisit', petvisit);
//---------------  Check if paused, if not, run autoplay logic loop
if (GM_getValue('paused')==0)
	{
//	while (flag == 0)
//		{
			logicTimer=window.setTimeout(logic, 3000);
//		}
	}
